package net.zjitc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.common.R;
import net.zjitc.entity.User;
import net.zjitc.service.UserService;
import net.zjitc.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*请求 URL: http://localhost:8080/user/sendMsg 请求方法: POST
     * phone: "13212345678"*/
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("请求验证码：" + user.getPhone());
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("code={}", code);
        //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
        //session.setAttribute(phone, code);
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    /**
     * code:"767767"
     * phone:"13212345678"
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session) {
        log.info("登录请求：" + map);
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //String codeInSession = session.getAttribute(phone).toString();
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        if (code.equals(codeInRedis)) {
            //登录成功
            //判断，当前用户是否已经在数据库中了，如果是第一次登录，则记录该用户数据到数据库中
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            log.info("用户id" + user.getId());
            redisTemplate.delete(phone);
            return R.success("登录成功");
        }
        return R.error("登录失败");
    }

    /**
     * 请求 URL: http://localhost:8080/user/loginout
     * 请求方法: POST
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("删除成功");
    }

}
